package com.beiing.tianshuai.tianshuai.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.DemoCache;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.app.MyApplication;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.dongtai.DynamicFragment;
import com.beiing.tianshuai.tianshuai.entity.CodeBean;
import com.beiing.tianshuai.tianshuai.entity.NoticeMarksBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.entity.VersionInfoBean;
import com.beiing.tianshuai.tianshuai.freshnews.DiscoveryDetailActivity;
import com.beiing.tianshuai.tianshuai.helper.PendingIntentHelper;
import com.beiing.tianshuai.tianshuai.huodong.ActivitiesDetailActivity;
import com.beiing.tianshuai.tianshuai.interest.InterestVideoDetailActivity;
import com.beiing.tianshuai.tianshuai.message.ui.MessageFragment;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.network.DataManager;
import com.beiing.tianshuai.tianshuai.nim.jsbridge.NotificationHelper;
import com.beiing.tianshuai.tianshuai.presenter.MainPresenter;
import com.beiing.tianshuai.tianshuai.rx.MsgEvent;
import com.beiing.tianshuai.tianshuai.rx.RxBus;
import com.beiing.tianshuai.tianshuai.service.EasemobService;
import com.beiing.tianshuai.tianshuai.service.UpdateAppService;
import com.beiing.tianshuai.tianshuai.util.FragmentFactory;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;
import com.beiing.tianshuai.tianshuai.view.MainViewImpl;
import com.beiing.tianshuai.tianshuai.widget.CheckVersionDialog;
import com.beiing.tianshuai.tianshuai.widget.DownLoadProgressDialog;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.friend.model.AddFriendNotify;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.SystemMessageObserver;
import com.netease.nimlib.sdk.msg.constant.SystemMessageType;
import com.netease.nimlib.sdk.msg.model.SystemMessage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.jpush.android.api.JPushInterface;
import cn.magicwindow.MLinkAPIFactory;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * 主页面
 *
 * @author 刘泽启
 * @date 2017/7/7
 */

public class MainActivity extends BaseActivity implements MainViewImpl {

    @BindView(R.id.home_container)
    FrameLayout homeContainer;

    /**
     * 底部导航栏
     */
    @SuppressLint("StaticFieldLeak")
    public static TabLayout bottomTabLayout;

    private static final String TAG = "MainActivity";
    public static final int SHOW_POINT = 0;
    public static final int HIDE_POINT = 1;
    private Unbinder mUnbinder;
    private Context mContext;
    private Fragment[] fragments;
    private String[] fragmentTags = {"0", "1", "2", "3", "4"};
    private Fragment mContentFragment;
    public TextView mTabView;
    private int mPreIndex;
    public static boolean isPublished;
    private DownLoadProgressDialog mProgressDialog;
    private int mFileLength;
    private String mAppName;
    private File mFile;
    private FragmentFactory mFragmentFactory;
    private long reselectTime = 0;
    private int reselectTabPosition;

    /**
     * 记录当前登录用户的id
     */
    private String mUid;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    private void initView() {
        bottomTabLayout = findViewById(R.id.bottom_tab_layout);
    }

    @Override
    protected void init() {

        mUnbinder = ButterKnife.bind(this);
        mContext = this;

        MLinkAPIFactory.createAPI(this).deferredRouter();

        mUid = UserInfoBean.getUid(mContext);

        //判断用户是否登录，如果登录用UID来设置推送别名
        if (!TextUtils.isEmpty(mUid)) {
            JPushInterface.setAlias(mContext, AppConstant.MSG_SET_ALIAS, mUid);
        }

        mFragmentFactory = new FragmentFactory();
        fragments = mFragmentFactory.getFragments();
        initView();
        Intent intent = getIntent();

        // 判断是否是从启动页点击进来需要跳转
        // 0-活动|1-视频|2-新鲜事|3-第三方|4-不跳转
        int intentType = intent.getIntExtra("intentType", -1);
        if (intentType != -1) {
            String url = intent.getStringExtra("url");
            switch (intentType) {
                case 0:
                    Intent intentToActivity = new Intent(mContext, ActivitiesDetailActivity.class);
                    intentToActivity.putExtra("active_id", url);
                    startActivity(intentToActivity);
                    break;
                case 1:
                    Intent intentToVideo = new Intent(mContext, InterestVideoDetailActivity.class);
                    intentToVideo.putExtra("vid", url);
                    startActivity(intentToVideo);
                    break;
                case 2:
                    Intent intentToDiscovery = new Intent(mContext, DiscoveryDetailActivity.class);
                    intentToDiscovery.putExtra("fresh_id", url);
                    startActivity(intentToDiscovery);
                    break;
                case 3:
                    Intent intentToWebView = new Intent(mContext, WebViewActivity.class);
                    intentToWebView.putExtra("url", url);
                    startActivity(intentToWebView);
                    break;
                default:
                    LogUtils.d("intent type is " + intentType, "intentType");
                    break;
            }
        }

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        if (mContentFragment == null) {
            mContentFragment = fragments[0];
            transaction.add(R.id.home_container, mContentFragment, fragmentTags[0]).commit();
        }

        bottomTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            private TabLayout.Tab mTabAt;

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                if (position == 3) {
                    String uid = UserInfoBean.getUid(mContext);
                    if (TextUtils.isEmpty(uid)) {
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        TabLayout.Tab tabAt = bottomTabLayout.getTabAt(mPreIndex);
                        if (tabAt != null) {
                            tabAt.select();
                        }
                        return;
                    }
                }
                onTabItemSelected(position);
                mPreIndex = position;
                for (int i = 0; i < bottomTabLayout.getTabCount(); i++) {
                    mTabAt = bottomTabLayout.getTabAt(i);
                    View view = null;
                    if (mTabAt != null) {
                        view = mTabAt.getCustomView();
                    }
                    TextView text;
                    ImageView img;
                    if (view != null) {
                        text = view.findViewById(R.id.tab_content_text);
                        img = view.findViewById(R.id.tab_content_image);
                        if (i == position) {
                            text.setTextColor(Color.parseColor("#67A0FF"));
                            img.setImageResource(FragmentFactory.TAB_ICON_SELECTED[i]);
                        } else {
                            text.setTextColor(ContextCompat.getColor(mContext, R.color.black));
                            img.setImageResource(FragmentFactory.TAB_ICON[i]);
                        }
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                switch (position) {
                    case 0:
                        break;
                    case 1:
                        break;
                    case 2:
                        /*
                         * 点击的时候获取当前时间
                         * 用当前时间减去上一次点击时间
                         *
                         * 如果小于1秒钟并且两次所选择的tab为同一个
                         *      调用返回顶部方法 然后上一次点击事件恢复为0
                         * 否则
                         *      不执行方法 重新记录position和time
                         */
                        long timeNow = System.currentTimeMillis();
                        if (timeNow - reselectTime < 1000 && reselectTabPosition == position) {
                            reselectTabPosition = -1;
                            reselectTime = 0;
                            Fragment fragment = fragments[2];
                            if (fragment instanceof DynamicFragment) {
                                DynamicFragment dynamicFragment = (DynamicFragment) fragment;
                                dynamicFragment.refreshDynamics();
                            }
                        } else {
                            reselectTabPosition = position;
                            reselectTime = timeNow;
                        }
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
            }
        });
        for (int i = 0; i < 5; i++) {
            bottomTabLayout.addTab(bottomTabLayout.newTab().setCustomView(mFragmentFactory.getTabView(this, i)));
        }
        // 创建聊天服务
        createEasemobService();
        initDialog();
        initPresenter();
        initListener();

        NimUIKit.login(new LoginInfo(UserInfoBean.getUid(mContext), UserInfoBean.getUserToken(mContext)), new RequestCallback<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo loginInfo) {
                String account = loginInfo.getAccount();
                DemoCache.setAccount(account);
                LogUtils.i("登录成功", TAG);
            }

            @Override
            public void onFailed(int i) {
                LogUtils.e("登录失败", TAG);
            }

            @Override
            public void onException(Throwable throwable) {
                LogUtils.e(throwable.getMessage(), throwable.getMessage());
            }
        });

        initSystemMessageObserver();
    }

    private void initSystemMessageObserver() {
        Observer<SystemMessage> systemMessageObserver = new Observer<SystemMessage>() {
            @Override
            public void onEvent(SystemMessage systemMessage) {
                if (systemMessage.getType() == SystemMessageType.AddFriend) {
                    AddFriendNotify attachData = (AddFriendNotify) systemMessage.getAttachObject();
                    if (attachData != null) {
                        // 针对不同的事件做处理
                        if (attachData.getEvent() == AddFriendNotify.Event.RECV_ADD_FRIEND_DIRECT) {
                            // 对方直接添加你为好友
                        } else if (attachData.getEvent() == AddFriendNotify.Event.RECV_AGREE_ADD_FRIEND) {
                            // 对方通过了你的好友验证请求
                        } else if (attachData.getEvent() == AddFriendNotify.Event.RECV_REJECT_ADD_FRIEND) {
                            // 对方拒绝了你的好友验证请求
                        } else if (attachData.getEvent() == AddFriendNotify.Event.RECV_ADD_FRIEND_VERIFY_REQUEST) {
                            // 对方请求添加好友，一般场景会让用户选择同意或拒绝对方的好友请求。
                            // 通过message.getContent()获取好友验证请求的附言
                            LogUtils.i("收到一条好友请求通知", TAG);
                            PendingIntent newFriendMessagePendingIntent = PendingIntentHelper.getNewFriendMessagePendingIntent(mContext, Notification.FLAG_AUTO_CANCEL);
                            NotificationHelper notificationHelper = new NotificationHelper(mContext);
                            Notification notification = notificationHelper.makeNotification(
                                    newFriendMessagePendingIntent,
                                    "收到一条好友请求",
                                    TextUtils.isEmpty(systemMessage.getContent()) ? "" : systemMessage.getContent(),
                                    "收到一条好友请求",
                                    R.drawable.logo_180,
                                    true,
                                    true
                            );
                            notificationHelper.notifyNotification(notification);
                            int newFriendCount = (int) SPUtils.get(mContext, "newFriendCount", 0);
                            SPUtils.put(mContext, "newFriendCount", newFriendCount++);
                            RxBus.getInstanceBus().post(new MsgEvent<>("messageNotice", newFriendCount + 1));
                        }
                    }
                }
            }
        };

        NIMClient.getService(SystemMessageObserver.class).observeReceiveSystemMsg(systemMessageObserver, true);
    }

    private void initListener() {
        View tabView = mFragmentFactory.getTabView(mContext, 2);
        tabView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    private void initPresenter() {
        MainPresenter presenter = new MainPresenter(this);
        String uid = UserInfoBean.getUid(mContext);
        if (!TextUtils.isEmpty(uid)) {
            presenter.getLoginState(uid);
        }
        presenter.getVersionInfo();
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
//        outState.putBoolean("isMainActivityDestroy", true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.i("onResume:", "MainActivity");

        // 当用户切换账号的时候重新加载对应的消息界面
        String uid = UserInfoBean.getUid(mContext);
        if (!TextUtils.equals(mUid, uid)) {
            mUid = uid;
            fragments[3] = new MessageFragment();
        }

        // 更新tabLayout上面的小红点
        if (!TextUtils.isEmpty(uid)) {
            loginIM();
            TabLayout.Tab tab = bottomTabLayout.getTabAt(3);
            if (tab != null) {
                View customView = tab.getCustomView();
                if (customView != null) {
                    mTabView = customView.findViewById(R.id.point_new_message);
                }
            }

            int totalUnreadCount = NIMClient.getService(MsgService.class).getTotalUnreadCount();

            updatePointUI(totalUnreadCount);
        }

        updateDynamicNewMessagePoint(mContext);

        if (isPublished) {
            // 发布动态返回主页面时刷新动态列表
            DynamicFragment.updateDynamicList();
            isPublished = false;
        }
    }

    public static void updateDynamicNewMessagePoint(Context context) {
        if (bottomTabLayout != null) {
            DisposableObserver<NoticeMarksBean> observer = new DisposableObserver<NoticeMarksBean>() {
                @Override
                public void onNext(@NonNull NoticeMarksBean bean) {
                    if (bean.getCode() == 200) {
                        int replyCount = bean.getData().getComment();
                        int praiseCount = bean.getData().getThing();
                        int sumCount = replyCount + praiseCount;
                        TabLayout.Tab tab = bottomTabLayout.getTabAt(2);
                        View customView = null;
                        if (tab != null) {
                            customView = tab.getCustomView();
                        }
                        TextView dynamicPoint = null;
                        if (customView != null) {
                            dynamicPoint = customView.findViewById(R.id.point_new_message);
                        }
                        if (dynamicPoint != null) {
                            if (sumCount > 0) {
                                dynamicPoint.setText(String.valueOf(sumCount));
                                dynamicPoint.setVisibility(View.VISIBLE);
                            } else {
                                dynamicPoint.setVisibility(View.GONE);
                            }
                        }
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    LogUtils.e("获取动态新消息数量失败 " + e.getMessage(), "MainActivity");
                }

                @Override
                public void onComplete() {
                    LogUtils.i("获取动态新消息数量完成", "MainActivity");
                }
            };

            DataManager.getNoticeMarksResult(UserInfoBean.getUid(context))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        }
    }

    public void updatePointUI(int unreadCount) {
        Message message = new Message();
        int isNewFriend = (int) SPUtils.get(mContext, "newFriendCount", 0);
        if (unreadCount > 0 || isNewFriend != 0) {
            message.what = SHOW_POINT;
            Bundle bundle = new Bundle();
            bundle.putInt("messageCount", unreadCount + isNewFriend);
            message.setData(bundle);
        } else {
            message.what = HIDE_POINT;
        }
        mHandler.sendMessage(message);
    }

    private void onTabItemSelected(int position) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        Fragment toFragment = fragments[position];
        if (mContentFragment != toFragment) {
            if (!toFragment.isAdded()) {
                transaction.hide(mContentFragment).add(R.id.home_container, toFragment, fragmentTags[position]).commit();
            } else {
                transaction.hide(mContentFragment).show(toFragment).commit();
            }
            mContentFragment = toFragment;
        }
    }

    /**
     * 按两次返回退出应用
     */
    private boolean doubleBackToExitPressedOnce = false;

    @Override
    public void onBackPressed() {
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed();
            return;
        }
        this.doubleBackToExitPressedOnce = true;
        showShortText("再按一次返回键退出");

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    private void loginIM() {
        NimUIKit.login(new LoginInfo(UserInfoBean.getUid(mContext), UserInfoBean.getUserToken(mContext)), new RequestCallback<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo loginInfo) {
                String account = loginInfo.getAccount();
                DemoCache.setAccount(account);
                LogUtils.i("登录成功", TAG);
            }

            @Override
            public void onFailed(int i) {
                LogUtils.e("登录失败", TAG);
            }

            @Override
            public void onException(Throwable throwable) {
                LogUtils.e(throwable.getMessage(), throwable.getMessage());
            }
        });
    }

    private void createEasemobService() {
        Intent intent = new Intent(this, EasemobService.class);
        startService(intent);
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case SHOW_POINT:
                    mTabView.setVisibility(View.VISIBLE);
                    int messageCount = message.getData().getInt("messageCount");
                    mTabView.setText(String.valueOf(messageCount > 99 ? "99+" : messageCount));
                    break;
                case HIDE_POINT:
                    if (mTabView != null) {
                        mTabView.setVisibility(View.GONE);
                    }
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    private Handler mUpdateHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case 100:
                    //更新dialog进度
                    int count = (int) message.obj;
                    mProgressDialog.setProgress(count);
                    float price = (float) count / (float) mFileLength * 100;
                    //构造方法的字符格式这里如果小数不足2位,会以0补足.
                    DecimalFormat decimalFormat = new DecimalFormat(".00");
                    //format 返回的是字符串
                    String p = decimalFormat.format(price);
                    mProgressDialog.setPercent("下载进度" + p + "%");
                    break;
                case 200:
                    //下载完成
                    if (mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                    }
                    //判读版本是否在7.0以上
                    if (Build.VERSION.SDK_INT >= 24) {
                        updateMoreThan7();
                    } else {
                        updateUnderAndroid7();
                    }
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    private void initDialog() {
        mProgressDialog = new DownLoadProgressDialog(mContext, R.style.dialog);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setListener(new DownLoadProgressDialog.OnClickListener() {
            @Override
            public void onBackGroundClickListener(View view) {
                showShortText("已转到后台下载最新版安装包");
                mProgressDialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onRequestSuccess(VersionInfoBean bean) {
        VersionInfoBean.DataBean.NumberBean versionBean = bean.getData().getNumber();
        int versionCode = Integer.valueOf(versionBean.getVersioncode());
        String versionName = versionBean.getVersionname();
        String description = versionBean.getDescription();
        mAppName = versionBean.getApk();
        checkUpdate(versionCode, versionName, description);
    }

    @Override
    public void onRequestFailed(Throwable throwable) {

    }

    private void checkUpdate(int versionCodeNow, String versionNew, String description) {
        int versionCodeNew = 0;
        try {
            versionCodeNew = mContext.getPackageManager().getPackageInfo("com.beiing.tianshuai.tianshuai", 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (versionCodeNew < versionCodeNow) {
            CheckVersionDialog dialog = new CheckVersionDialog(mContext, R.style.dialog, new CheckVersionDialog.OnCloseListener() {
                @Override
                public void onClick(Dialog dialog, boolean confirm, int id) {
                    if (confirm) {
                        switch (id) {
                            case R.id.btn_update_now:
                                mProgressDialog.setCancelable(false);
                                mProgressDialog.setCanceledOnTouchOutside(false);
                                mProgressDialog.show();
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        downloadFile(); // 开始下载
                                    }
                                }).start();
                                break;
                            case R.id.btn_update_background:
                                showShortText("已转到后台下载最新版安装包");
                                Intent intent = new Intent(mContext, UpdateAppService.class);
                                intent.putExtra("app_name", mAppName);
                                intent.putExtra("url", HttpRequestConstant.REQUEST_DOWNLOAD_APK + mAppName);
                                mContext.startService(intent);
                                break;
                            default:
                                break;
                        }
                    }
                    dialog.dismiss();
                }
            }).setContent(description).setVersionName("是否升级到" + versionNew + "版本？");
            dialog.show();
        }
    }

    private void downloadFile() {
        try {
            URL url = new URL(HttpRequestConstant.REQUEST_DOWNLOAD_APK + mAppName);
            LogUtils.i(HttpRequestConstant.REQUEST_DOWNLOAD_APK + mAppName, "apkURL");
            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                InputStream inputStream = conn.getInputStream();
                mFileLength = conn.getContentLength();
                mProgressDialog.setMax(mFileLength);
                String dir = Environment.getExternalStorageDirectory() + "/TianShuai/天率校园/";
                File apkDir = new File(dir);
                if (!apkDir.exists()) {
                    if (apkDir.mkdirs()) {
                        LogUtils.i("创建路径 “/TianShuai/天率校园/” 成功", "make dir");
                    } else {
                        LogUtils.e("创建路径 “/TianShuai/天率校园/” 失败", "make dir");
                    }
                }
                String path = dir + mAppName;
                mFile = new File(path);
                FileOutputStream fileOutputStream = new FileOutputStream(mFile);
                int length;
                int progress = 0;
                byte[] bytes = new byte[1024];
                while ((length = inputStream.read(bytes)) != -1) {
                    fileOutputStream.write(bytes, 0, length);
                    progress += length;
                    Message msgUpdateProgress = new Message();
                    msgUpdateProgress.what = 100;
                    msgUpdateProgress.obj = progress;
                    mUpdateHandler.sendMessage(msgUpdateProgress);
                }
                inputStream.close();
                fileOutputStream.close();
                fileOutputStream.flush();
                Message msgDownloadFinish = new Message();
                msgDownloadFinish.what = 200;
                mUpdateHandler.sendMessage(msgDownloadFinish);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 适配Android7版本以下安装程序
     */
    private void updateUnderAndroid7() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), mAppName)),
                "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 适配Android7版本以上安装程序
     */
    private void updateMoreThan7() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri apkURI = FileProvider.getUriForFile(mContext, "com.beiing.tianshuai.fileprovider", mFile);
        intent.setDataAndType(apkURI, "application/vnd.android.package-archive");
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
    }

    @Override
    public void getLoginState(CodeBean bean) {
        int code = bean.getCode();
        if (code == 406) {
            SPUtils.clear(mContext);
            NimUIKit.logout();
            JPushInterface.setAlias(mContext, 0, null);
        }
    }

    /**
     * 通过 onActivityResult的方法获取扫描回来的值
     *
     * @param requestCode 请求码
     * @param resultCode  结果码
     * @param data        数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (intentResult != null) {
            if (intentResult.getContents() == null) {
                Toast.makeText(this, "内容为空", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "扫描成功", Toast.LENGTH_LONG).show();
                // ScanResult 为 获取到的字符串
                String scanResult = intentResult.getContents();
                LogUtils.i(scanResult, TAG);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}